import 'dart:async';
import 'package:fluid_dialog/fluid_dialog.dart';
import 'package:flutter/material.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:go_router/go_router.dart';
import 'package:provider/provider.dart';
import 'package:sentry_flutter/sentry_flutter.dart';
import 'package:sites_hub/header_page.dart';
import 'package:sites_hub/horizon_navigation.dart';
import 'package:sites_hub/pages/site_page.dart';
import 'package:sites_hub/task.dart';
import 'package:window_manager/window_manager.dart';
import 'package:windows_notification/notification_message.dart';
import 'package:windows_notification/windows_notification.dart';

import 'pages/note_page.dart';
import 'pages/page_manager.dart';
import 'utils.dart';

void main() async {
  await SentryFlutter.init((options) {
    options.dsn =
        'https://b869e34ff1a9536d18559c9614d6d84e@o4507980179767296.ingest.de.sentry.io/4507980196020304';
    options.tracesSampleRate = 1.0;
    options.profilesSampleRate = 1.0;
  }, appRunner: () => run());
}

Future<void> run() async {
  await windowInit();
  await dbInit();
  runApp(MultiProvider(
    providers: [
      ChangeNotifierProvider(create: (context) => IndexedIndicator()),
      ChangeNotifierProvider(create: (context) => SiteDataProvider()),
      ChangeNotifierProvider(create: (context) => ContentProvider()),
      ChangeNotifierProvider(create: (context) => EditorStateProvider()),
      ChangeNotifierProvider(create: (context) => TaskListProvider()),
      ChangeNotifierProvider(create: (context) => TimeProvider()),
    ],
    child: DragToMoveArea(child: MyApp()),
  ));
}

class MyApp extends StatelessWidget {
  MyApp({super.key});

  final GoRouter _router = GoRouter(initialLocation: '/home', routes: [
    GoRoute(
        path: '/home',
        builder: (c, s) {
          return const MyHomePage(title: 'Flutter Demo Home Page');
        })
  ]);

  @override
  Widget build(BuildContext context) {
    return MaterialApp.router(
      debugShowCheckedModeBanner: false,
      routerConfig: _router,
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  void initState() {
    super.initState();
    Timer.periodic(const Duration(minutes: 1), (_) {
      print('notify');
      var list = context.read<TaskListProvider>().newTaskList.where((it) {
        return it.status == TaskStatus.New;
      }).toList();
      list.forEach((Task it) {
        var c = it.taskContent;
        String template = '''
<toast activationType="protocol">
  <visual>
    <binding template="ToastGeneric">
      <text>Weather app</text>
      <text>Expect rain today.</text>
      <group>
        <subgroup hint-weight="1" hint-textStacking="center">
          <text hint-align="center" hint-style="header">$c</text>
          <text hint-align="center" hint-style="SubtitleSubtle">Rainy</text>
        </subgroup>
      </group>
    </binding>
  </visual>
</toast>
''';

        NotificationMessage message = NotificationMessage.fromCustomTemplate(
            "notificationid_1",
            group: "weather_group");
        _winNotifyPlugin.showNotificationCustomTemplate(message, template);
      });
    });
  }

  TextEditingController controller = TextEditingController();
  var site_name = '';
  var icon_url = '';
  var site_url = '';
  Offset offset = const Offset(0, 0);
  var _x;
  var _y;

  final _winNotifyPlugin = WindowsNotification(
      applicationId:
          r"{D65231B0-B2F1-4857-A4CE-A8E7C6EA7D27}\WindowsPowerShell\v1.0\powershell.exe");

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: const BoxDecoration(
            image: DecorationImage(
          opacity: 0.8,
          image: NetworkImage(
              'https://files.codelife.cc/wallpaper/wallspic/202311150d4c82.jpeg?x-oss-process=image/resize,limit_0,m_fill,w_2560,h_1440/quality,Q_92/format,webp'),
          fit: BoxFit.cover,
        )),
        child: Column(
          children: [
            HeaderPage(),
            Expanded(
              child: PageManager.go(context.watch<IndexedIndicator>().page),
              // child: context.watch<IndexedIndicator>().index == 0
              //     ? SitePage()
              //     : NotePage(),
            ),
            HorizonNavigation(),
          ],
        ),
      ),
      floatingActionButton: IconButton.outlined(
          onPressed: () {
            //    await DB.instance.database.execute('''
            //    CREATE TABLE IF NOT EXISTS RuneConfig
            // (id INTEGER PRIMARY KEY autoincrement, heroId TEXT, name TEXT, content TEXT)
            //    ''');
            print('execute sucess');
            showDialog(
              context: context,
              builder: (context) => FluidDialog(
                rootPage: FluidDialogPage(
                  alignment: Alignment.center,
                  builder: (context) => Container(
                    height: 300,
                    width: 300,
                    color: Colors.pinkAccent,
                  ),
                ),
              ),
            );
          },
          icon: const Icon(
            Icons.settings,
            color: Colors.white,
          )),
    );
  }
}

class SiteItem {
  String siteName;
  String iconUrl;
  String siteUrl;

  SiteItem(
      {required this.siteName, required this.iconUrl, required this.siteUrl});
}
